<?php
namespace app\models;

use yii\db\ActiveRecord;

/**
 * 用户消息
 *
 * Class UserMessage
 * @package app\models
 *
 * @property integer $id
 * @property integer $uid
 * @property integer $sid
 * @property integer $from_uid
 * @property integer $time
 * @property string $title
 * @property string $content
 * @property integer $status
 */
class UserMessage extends ActiveRecord
{
    const STATUS_NEW = 1;
    const STATUS_OLD = 9;
    const STATUS_DEL = 0;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uid', 'time', 'title', 'content', 'status'], 'required'],
            ['title', 'string', 'max'=>256],
            [['sid', 'from_uid'], function($attribute, $params) {
                if (empty($this->sid) && empty($this->from_uid)) {
                    $this->addError('sid', '不能为空。');
                    $this->addError('from_uid', '不能为空。');
                }
            }],
        ];
    }

    /**
     * 检查新消息
     * @param integer $uid
     * @return boolean 是否有更新
     */
    public static function checkNew($uid)
    {
        $sid = SystemMessage::find()->max('id');
        if ($sid == 0) {
            return false;
        }
        $usid = UserMessage::find()->where(['uid'=>$uid])->max('sid');
        $usid = intval($usid);
        if ($usid >= $sid) {
            return false;
        }
        foreach (SystemMessage::find()->where(['>', 'id', $usid])->each() as $system_message) {
            $user_message = new UserMessage();
            $user_message->uid = $uid;
            $user_message->sid = $system_message->id;
            $user_message->from_uid = null;
            $user_message->time = $system_message->time;
            $user_message->title = $system_message->title;
            $user_message->content = $system_message->content;
            $user_message->status = UserMessage::STATUS_NEW;
            $user_message->save();
        }
        return true;
    }
}
